「今天我們要把前端跟後端接起來,使用者輸入城市,按下查詢就可以看到即時天氣與圖示。這才是真正能運作的小工具!」
內容重點:
/weather
程式說明:
const res = await fetch(`/weather?city=${city}`);
const data = await res.json();
if (data.error) {
document.getElementById("result").innerText = "❌ " + data.error;
} else {
document.getElementById("result").innerHTML = `
<strong>${data.name}</strong><br>
<img src="http://openweathermap.org/img/wn/${data.icon}@2x.png" alt="weather icon">
🌡️ 溫度: ${data.temp}°C <br>
☁️ 天氣: ${data.description}
`;
}
解析:整合完成後,前端與後端真正合作,畫面能顯示即時資料。